package client.ui;

import client.RepositoryDTO;

import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class RepositoryEditingDialogBox extends AbstractTwoButtonDialogBox {
	
	private TextBox nameTextBox;
	private TextBox urlTextBox;
	private TextBox usernameTextBox;
	private PasswordTextBox passwordTextBox;
	private long id = 0;
	
	@Override
	protected void customSetup() {
		setText("Edit Repository");
		nameTextBox = new TextBox();
		urlTextBox = new TextBox();
		usernameTextBox = new TextBox();
		passwordTextBox = new PasswordTextBox();
	}

	@Override
	protected void populateVerticalPanel(final VerticalPanel vp) {
		final Grid grid = new Grid(4, 2);
		populateGridWithWidget(grid, 0, "Name", nameTextBox);
		populateGridWithWidget(grid, 1, "URL", urlTextBox);
		populateGridWithWidget(grid, 2, "Username", usernameTextBox);
		populateGridWithWidget(grid, 3, "Password", passwordTextBox);
		vp.add(grid);
	}
	
	private void populateGridWithWidget(final Grid grid, int row, String caption, Widget widget) {
		final Label label = new Label(caption);
		label.setHorizontalAlignment(Label.ALIGN_RIGHT);
		grid.setWidget(row, 0, label);
		grid.setWidget(row, 1, widget);
	}

	public void displayRepository(final RepositoryDTO repositoryDTO) {
		id = repositoryDTO.getId();
		nameTextBox.setText(repositoryDTO.getName());
		urlTextBox.setText(repositoryDTO.getUrl());
		usernameTextBox.setText(repositoryDTO.getUsername());
		passwordTextBox.setText("");
	}
	
	public RepositoryDTO getRepository() {
		final RepositoryDTO repositoryDTOForUpdate = new RepositoryDTO();
		repositoryDTOForUpdate.setId(id);
		repositoryDTOForUpdate.setName(nameTextBox.getText());
		repositoryDTOForUpdate.setUrl(urlTextBox.getText());
		repositoryDTOForUpdate.setUsername(usernameTextBox.getText());
		repositoryDTOForUpdate.setPassword(passwordTextBox.getText());
		return repositoryDTOForUpdate;
	}
}
